<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Request;

class AuthorizationMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(!config('maqu.APP_DEBUG',false)){

            //check paramters
            $access_token = Request::input('access_token');
            $user_id = Request::input('user_id');

            if(empty($access_token) || empty($user_id)){
                return response()->json(array(
                    'status' => RESPONSE_ARGUMENT_INVALID,
                    'code'=>'',
                    'message' => '非法参数(登陆认证)',
                    'auth_failure' => AUTH_FAILURE_YES,
                    'data' => []
                ), 200);
            }

            //check access_token option (access_token and user_id )
            $result = $this->check_access_token($request,$access_token,$user_id);
            if($result!==true){
                return $result;
            }
        }

        return $next($request);
    }

    private function check_access_token($request,$access_token,$user_id){

//        $user =DB::table('member')
//            ->where('user_id',$user_id)->first();
        $user= User::find($user_id);

        if(!$user){
            return response()->json(array(
                'status' => RESPONSE_FAILURE,
                'code'=>'',
                'message' => '用户不存在',
                'auth_failure' => AUTH_FAILURE_YES,
                'data' => []
            ), 200);
        }

        $user_safe=DB::table('user_safe')
            ->where('user_id',$user_id)->first();

        if(!$user_safe){
            return response()->json(array(
                'status' => RESPONSE_FAILURE,
                'code'=>'',
                'message' => '用户不存在',
                'auth_failure' => AUTH_FAILURE_YES,
                'data' => []
            ), 200);
        }

        $now = gmtime();

        //密码
        //access_token
        //expire_time
        if(($user_safe->login_pwd!==$user->password) ||
            ($user_safe->access_token!==$access_token) ||
            ($now > $user_safe->expire_time)){
            return response()->json(array(
                'status' => RESPONSE_FAILURE,
                'code'=>'',
                'message' => '您的登录信息已经过期，请重新登录',
                'auth_failure' => AUTH_FAILURE_YES,
                'data' => []
            ), 200);
        }

        //保存用户信息（后续处理里就不需要重新检索用户了）
        $request->user = $user;

        //更新该用户的登录信息过期时间

        DB::table('user_safe')
            ->where('user_id',$user_id)
            ->update(['expire_time'=>$now+config('maqu.LOGIN_VALID_PERIOD',7)*24*60*60]);

        return true;

    }

}
